package com.yfqy.admin.resource;

import com.yfqy.admin.concurrency.StockService;
import com.yfqy.admin.domain.dto.OrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 梁二东
 * @Date: 2025/5/5 11:25
 * @Description:
 **/
@RestController
public class TestController {


    @Autowired
    private StockService stockService;

    @PostMapping("/api/noauth/create")
    public ResponseEntity<String> createOrder(@RequestBody List<OrderRequest> orderRequest) {
        // orderRequest.skuIdToNum: Map<Long, Integer>
        Map<Long, Integer> skuIdToNum = new HashMap<>();
        orderRequest.forEach(req -> {
            skuIdToNum.put(req.getSkuId(), req.getNum());
        });
        boolean success = stockService.deductMultiStock(skuIdToNum);
        if (success) {
            // TODO: 创建订单、异步/定时同步库存到DB
            return ResponseEntity.ok("下单成功");
        } else {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("库存不足，下单失败");
        }
    }

    @GetMapping(value = {"/api/noauth"})
    public String hello(@RequestParam(name = "name", required = false) String name) {
        if (StringUtils.hasLength(name)) {
            return "hello " + name;
        }
        return "hello Unknown";
    }

    @GetMapping(value = {"/say/hello", "/api/internal"})
    // @PreAuthorize("hasAuthority('user:list')")
    public String hello1(@RequestParam(name = "name", required = false) String name) {
        if (StringUtils.hasLength(name)) {
            return "hello " + name;
        }
        return "hello Unknown";
    }


    @GetMapping(value = {"/say/hello/2", "/api/internal/2"})
    // @PreAuthorize("hasAuthority('user:add')")
    public String hello2(@RequestParam(name = "name", required = false) String name) {
        if (StringUtils.hasLength(name)) {
            return "hello " + name;
        }
        return "hello Unknown";
    }
}
